$(function () {
    //高级搜索
    bonusPoints();

    //初始化专业搜索条件
    $.initSubject({
        element:'subject-box',
        confirmBtn:false,
        removeBtn: false,
        style:false,
        notMultiple:true,
        classText:'form-control mb10',
        width:100,
        selectCallback:function(subjectIds){
            $("#subjectIds").val(subjectIds);
        }
    });

    //页面加载完成获取第一页数据
    queryAjaxUserList(1);
    $('body').on('click','#submitFrom,#querySubmit',function () {
        //点击搜索查询从第一页开始查询
        queryAjaxUserList(1);
    }).on('click', '.selectCourse', function () {
        userId = $(this).data('id');
        selectCourse({
            selectType:"checkbox",
            type:1,
            callback:'selectCourseCallback'
        });
    }).on('click','#resetPassword',function () {
        var userId = $(this).data('id');
        resetUserPassword(userId);
    }).on('click','#unlockAndHistory',function () {//单个搜索
        var userIds = $(this).data('id');
        var isavalible = $(this).data('isavalible');
        var obj = $(this);
        if(isavalible==1){
            updateUserStatusByUserIds(userIds, obj, 2);
        }
        if(isavalible==2){
            updateUserStatusByUserIds(userIds, obj, 1);
        }
    }).on("click","#unlockBatch",function () {//批量冻结
        var obj = $("input[name='userId']:checked");
        var userIds = obtainIds(obj);//获取勾选ids
        if(!$.isEmptyObject(userIds)){
            updateUserStatusByUserIds(userIds, obj ,2 );
        }
    }).on("click","#historyBatch",function () {//批量恢复
        var obj = $("input[name='userId']:checked");
        var userIds = obtainIds(obj);//获取勾选ids
        if(!$.isEmptyObject(userIds)){
            updateUserStatusByUserIds(userIds, obj, 1);
        }
    }).on('click','#sign-out',function () {
        var userId = $(this).data('id');
        icModale(2,'确认要强制该学员退出登录？',3,function () {
            $.ajax({
                url:baseloaction +'/admin/user/cus/forceUserSignOut',
                type:'post',
                dataType:'json',
                data:{
                    'userId':userId
                },
                success:function (result) {
                    icModale(0,result.message);
                },
                error:function (error) {
                    icModale(0,'系统错误，强制退出学员登录失败');
                }
            });
        });
    });
    //判断勾选ID是否为空
    function obtainIds(obj) {
        if (obj.size() == 0) {
            icModale(0,"请选择要批量操作的数据");
            return null;
        } else {
            var userIds = "";
            obj.each(function (index, em) {
                userIds += em.value + ",";
            });
            userIds = userIds.substr(0, userIds.length - 1);
            return userIds;
        }
    }
    initTime("startDate","endDate","");
});

/**
 * 获取用户列表页面
 * @param pageNo 当前页码
 */
function queryAjaxUserList(pageNo) {
    var params = $("#search-form").serializeJSON();
    params = JSON.stringify(params);
    var obj = {
        url: baseloaction + '/admin/user/cus/ajaxUserListPage',//请求URL
        contextId: 'user-list-context',//响应内容页面设置内容ID
        params: params,//请求参数
        pageNo: pageNo,//页码
        pageCall: queryAjaxUserList, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
        selectAllId: 'select-all-user', //全选框ID
        callback: function () {//数据加载完成回调

        }
    };
    ajaxGetListData(obj);
}

 /**
     * 批量封禁，批量恢复
     * @param userIds
     * @param obj
     * @param isavalible
     */
function updateUserStatusByUserIds(userIds, obj, isavalible) {
        $.ajax({
            url: baseloaction + "/admin/user/cus/updateCusUserStatus",
            data: {"userIds": userIds, "status": isavalible},
            type: "post",
            dataType: "json",
            success: function (result) {
                if (result.success) {
                    if (2 == isavalible) {
                        obj.parents('tr').find('.isavalible').html('');
                        obj.parents('tr').find('.isavalible').append('<span class="label label-danger">禁封</span>');
                        obj.parents('tr').find("#unlockAndHistory").html("");
                        obj.parents('tr').find("#unlockAndHistory").data('isavalible', '2');
                        obj.parents('tr').find("#unlockAndHistory").append('<i class="fa fa-history"></i>')
                        obj.parents('tr').find("#unlockAndHistory").attr("data-original-title","恢复登录");
                    }
                    if (1 == isavalible) {
                        obj.parents('tr').find('.isavalible').html('');
                        obj.parents('tr').find('.isavalible').append('<span class="label label-info">正常</span>');
                        obj.parents('tr').find("#unlockAndHistory").html("");
                        obj.parents('tr').find("#unlockAndHistory").data('isavalible', '1');
                        obj.parents('tr').find("#unlockAndHistory").append('<i class="fa fa-unlock-alt"></i>')
                        obj.parents('tr').find("#unlockAndHistory").attr("data-original-title","禁封登录");
                    }
                } else {
                    icModale(0, result.message);
                }
            },
            error: function (error) {
                icModale(0, "系统繁忙,请稍后重试");
            }
        })
    }
/**
 * 重置用户密码
 */
function resetUserPassword(userId) {
    var index = parent.layer.open({
        type: 1,
        area: ['380px'],
        skin: 'layui-layer-demo',
        title: '重置密码',
        content: '<div class="m-t m-r m-l m-b"><input class="form-control"  value="" id="rPassword" name="" type="text" placeholder="请输入重置密码"></div>',
        btn: '确定',
        yes: function (index, layero) {
            var rPassword = layero.find('#rPassword').val();
            if(rPassword==null){
                return icModale(0, "请输入重置密码");
            }
            $.ajax({
                url:  baseloaction + "/admin/user/cus/resetPassword",
                type: "post",
                data: {"userId": userId, "rPassword": rPassword},
                dataType: "json",
                success: function (result) {
                    if (result.success == true) {
                        icModale(0, result.message);
                        parent.layer.close(index);
                    } else {
                        icModale(0, result.message);
                    }
                },
                error: function (error) {
                    icModale(0, '系统繁忙，请稍后再试');
                }
            });
        }
    });
}
//表格中单个字段的修改添加奖励积分
function bonusPoints() {
    $('body').on('click', '#resetdBtn', function() {
        var   id = $(this).data('id');
        var index = parent.layer.open({
            type: 1,
            area: ['380px'],
            skin: 'layui-layer-demo',
            title: '奖励积分',
            content: '<div class="m-t m-r m-l m-b"><input class="form-control" maxlength="5" value="" id="userScore" name="" type="text" placeholder="请输入您要奖励的积分"></div>',
            btn: '确定',
            success:function(layero){
                layero.find("#userScore").on('keyup',function () {
                    var _this = $(this);
                    var reg = /^[1-9]{1}[0-9]*$/;
                    if(!reg.test(_this.val())){
                        _this.val("");
                    }
                });
            },
            yes: function(index, layero) {
                var userScore = layero.find('#userScore').val();
                if(!isNumber(userScore)){
                    return icModale(0, "请正确输入奖励积分");
                }
                if(userScore==0){
                    return icModale(0, "赠送积分不能为0");
                }
                $.ajax({
                    url:baseloaction+"/admin/user/cus/addUserIntegral",
                    type:"post",
                    data:{"userId":id,"score":userScore},
                    dataType:"json",
                    success:function (result) {
                        parent.layer.close(index);
                        if (result.success == true) {
                            icModale(0,result.message);
                        } else {
                            icModale(0,result.message);
                        }
                    },
                    error:function (error) {
                        parent.layer.close(index);
                        icModale(0,'系统繁忙，请稍后再试');
                    }
                });
            }
        });
    });

}